package abel.wlmr.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import abel.util.HexString;
import abel.wlmr.config.MeterStation;
import abel.wlmr.config.MsaConfig;
import abel.wlmr.config.MsaConfigLoader;
import abel.wlmr.model.WlmrPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class WlmrPacketEncoder extends MessageToByteEncoder<WlmrPacket> {
    private Logger log;

    public WlmrPacketEncoder() {
        MsaConfig cfg = MsaConfigLoader.getMsaConfig();
        log = LoggerFactory.getLogger(cfg.getMain().getA1().getAsc());
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, WlmrPacket msg, ByteBuf out) throws Exception {
        // build log for station.
        MeterStation station = ctx.channel().attr(PacketConsts.stationKey).get();
        if (station != null) {
            log = LoggerFactory.getLogger(station.getAddr().stationKey());
        }

        try {
            msg.appendBuf(out);

            log.warn("Down {}: {}\nHex: {}", msg.getAfn(), msg, HexString.bytesToHexStringWithBlank(out.duplicate()));
        } catch (Exception e) {
            log.error("Fail to encode caused by {}", e.getMessage());
            throw e;
        }
    }

}
